
package com.sm.shoplook.controller.system;

import com.github.pagehelper.PageInfo;
import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.domain.system.User;
import com.sm.shoplook.service.system.UserService;
import com.sm.shoplook.vo.base.ApiException;
import com.sm.shoplook.vo.base.ApiResult;
import com.sm.shoplook.vo.system.user.req.UserPageSearchReqVo;
import com.sm.shoplook.vo.system.user.req.UserSaveReqVo;
import com.sm.shoplook.vo.system.user.resp.UserRoleRespVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenpy
 * @desc 用户Controller
 * @date 2018/8/7 14:20
 * @see
 */
@RequestMapping("/user")
@Controller
public class UserController {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/manager", method = RequestMethod.GET)
	public String userManager() {
		return "/user/user_manager";
	}

	/**
	 * 登录
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ApiResult login(String userName, String password, HttpServletRequest request) throws ApiException {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		token.setRememberMe(true);
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			throw new ApiException(ResultMessage.ACCOUNT_NOT_FOUND_1000);
		} catch (DisabledAccountException e) {
			throw new ApiException(ResultMessage.DISABLEDA_CCOUNT_1001);
		} catch (IncorrectCredentialsException e) {
			throw new ApiException(ResultMessage.INCORRECT_CREDENTIALS_1002);
		}
		subject.hasRole("super_manager");
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}

	@ResponseBody
	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public ApiResult<Map<String, Object>> tableData(UserPageSearchReqVo userSearchReqVo) {
		ApiResult<Map<String, Object>> result = new ApiResult<>();
		result.setCode(1);
		result.setMessage("操作成功");
		Map<String, Object> map = new HashMap<>();
		ApiResult<PageInfo<User>> pageInfoApiResult = userService.selectUsersPage(userSearchReqVo);
		PageInfo<User> pageInfo = pageInfoApiResult.getData();
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		result.setData(map);
		return result;
	}

	@RequestMapping(value = "/save_user_page/{userId}", method = RequestMethod.GET)
	public String addOrUpdateUserPage(@PathVariable(value = "userId") Integer userId, Model model) {
		LOGGER.info("userId: {}", userId);
		ApiResult<UserRoleRespVo> userRoleRespVoApiResult = userService.selectUserRoleByUserId(userId);
		UserRoleRespVo user = userRoleRespVoApiResult.getData();
		if (user == null) {
			user = new UserRoleRespVo();
			user.setSex("M");
		}
		model.addAttribute("user", user);
		return "/user/add_update_user";
	}

	@RequiresPermissions("user_delete")
	@ResponseBody
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	public ApiResult<String> deleteUser(String ids) {
		ApiResult<String> result = new ApiResult<>();
		String[] idList = ids.split(",");
		// 批量删除
		LOGGER.info("ids", ids);
		try {
			return userService.deleteUsers(idList);
		} catch (ApiException e) {
			e.printStackTrace();
			LOGGER.error("e: {}", e);
			return new ApiResult(ResultMessage.RESULT_ERROR_0);
		}
	}

	@RequiresPermissions({ "user_add", "user_update" })
	@ResponseBody
	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	public ApiResult saveUser(UserSaveReqVo userSaveReqVo) {
		LOGGER.info("userSaveReqVo", userSaveReqVo);
		try {
			return userService.saveUser(userSaveReqVo);
		} catch (ApiException e) {
			e.printStackTrace();
			LOGGER.error("e: {}", e);
			return new ApiResult(ResultMessage.RESULT_ERROR_0);
		}
	}
}
